package com.hontech.pserver

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout


private fun hideSoftKey(activity: Activity) {
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (!imm.isActive) {
        return
    }
    val view = activity.currentFocus ?: return
    imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}


open class BaseActivity : AppCompatActivity() {


    companion object {
        lateinit var INSTANCE: BaseActivity
            private set

        fun parentView(): View {
            return INSTANCE.window.decorView
        }
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null

    private var actionDownTimestamp = 0L

    @SuppressLint("MissingSuperCall")
    override fun onConfigurationChanged(newConfig: Configuration) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        INSTANCE = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            hideSoftKey(this)
            actionDownTimestamp = System.currentTimeMillis()
        } else if (ev.action == MotionEvent.ACTION_UP) {
            val current = System.currentTimeMillis()
            if ((current - actionDownTimestamp) > 2000) {
                actionDownTimestamp = current
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun restart() {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        finish()
    }

    fun hideButton() {
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty()) {
            permissionFuture?.complete(grantResults[0] == PackageManager.PERMISSION_GRANTED)
        }
    }

    suspend fun requestPermission(permission: String) {


        val future = CompletableDeferred<Boolean>()
        permissionFuture = future
        requestPermissions(arrayOf(permission) , 0)
        try {
            withTimeout(10 * 1000) { future.await() }
        } catch (e: TimeoutCancellationException) {
            throw IllegalStateException("等待授权超时")
        }
    }
}

